package com.neusoft.mid.msf.gate.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * @program: pangu
 * @description: 动态路由的配置类,只有激活@EnableDynamicRoute注解,此类才会被加载
 * @author: fengjd
 * @create: 2022-07-26 19:08
 **/

@Configuration
@ConditionalOnProperty(prefix = "msf.gate.route",value = "enable",matchIfMissing = true)
@EnableConfigurationProperties(DynamicRouteProperties.class)
public class GateWayConfiguration {

    @ConditionalOnProperty
    @Bean
    public ConfigService routeConfigService(NacosConfigProperties nocosConfigProperties) throws NacosException {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nocosConfigProperties.getServerAddr());
        ConfigService configService = new NacosConfigService(properties);
        return configService;
    }

    @Bean
    public RouteDefinitionRepository customerRouteDefinitionRepository(DynamicRouteProperties dynamicRouteProperties,ConfigService configService)  {
        return new NacosRouteDefinitionRepository(dynamicRouteProperties, configService);
    }
}
